package civicinity.ist.psu.edu.share;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONObject;

import civicinity.ist.psu.edu.R;
import civicinity.ist.psu.edu.constants.Constants;
import civicinity.ist.psu.edu.databases.CivicinityDatabase;
import civicinity.ist.psu.edu.rssfeed.RSSReader;
import civicinity.ist.psu.edu.utils.CivicinityDrawableManager;
import civicinity.ist.psu.edu.utils.DownloadHandler;
import civicinity.ist.psu.edu.utils.UploadHandler;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class CivicinityShareInfo extends Activity {

	private int mEventID;
	private CivicinityDatabase mDB;
	
	private ImageView mPhotoImg;
	private TextView mDescription;
	private TextView mDate;
	private TextView mUsername;
	private TextView mCategory;
	private TextView mCommentCnt;
	private TextView mRecommendTxt;
	private TextView mUsernameTxt;
	private TextView mCheckinNumTxt;
	private EditText mCommentTxt;
	
	private Button mCheckInBtn;
	private Button mRecommendBtn;
	private Button mCommentBtn;
	private Button mSeeCommentBtn;
	
	private ProgressBar mSpinner;
	private TextView mSpinnerTxt;
	
	private int mCommentCntValue;
	
	private LinearLayout mGlobalLinearLayout;
	private RelativeLayout mGlobalRelativeLayout;
	private ProgressDialog mProgress;
	
	private SharedPreferences mPref;
	
	private double mLatitude;
	private double mLongitude;
	private LocationManager mLocManager;
	
	private ShareItem item;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.share_info_view);

	    // get previous intent
	    Intent gIntent = getIntent();
	    mEventID = gIntent.getExtras().getInt("event_id");
	    
	    // open database
	    mDB = new CivicinityDatabase(this);
	    mPref = PreferenceManager.getDefaultSharedPreferences(this);

	    // set up the layout
	    mPhotoImg = (ImageView) findViewById(R.id.photo);
	    mDescription = (TextView) findViewById(R.id.description);
	    mDate = (TextView) findViewById(R.id.date);
	    mSpinner = (ProgressBar) findViewById(R.id.progressbar);
	    mSpinnerTxt = (TextView) findViewById(R.id.progress_text);
	    mCheckinNumTxt = (TextView) findViewById(R.id.checkin_text);
	    mCommentCnt = (TextView) findViewById(R.id.num_comment);
	    mCommentTxt = (EditText) findViewById(R.id.user_comment);
	    mCommentBtn = (Button) findViewById(R.id.post_comment);
	    mRecommendTxt = (TextView) findViewById(R.id.like_text);
	    mUsernameTxt = (TextView) findViewById(R.id.username);
	    mRecommendBtn = (Button) findViewById(R.id.like_button);
	    mSeeCommentBtn = (Button) findViewById(R.id.see_comment);
	    mCheckInBtn = (Button) findViewById(R.id.checkin_button);
	    
	    // initialize layout to link dynamically added views
	    mGlobalRelativeLayout = (RelativeLayout)findViewById(R.id.dynamic_layout);
	    mGlobalLinearLayout = new LinearLayout(CivicinityShareInfo.this);
	    
	    // TODO Auto-generated method stub
	}
	
	@Override
	public void onResume() {
		super.onResume();
		
		item = new ShareItem();
	    item = mDB.getSingleShareOthers(mEventID);

	    // update username
	    mUsernameTxt.setText(item.getEventUsername());
	    
	    mCommentCntValue = item.getEventCommentCnt();
	    // for photo image
	    // If there's a cached image in the sdcard, retrieve it; otherwise, show that on the webpage 
		String imagePath = Constants.DOWNLOAD_SHARE_IMAGE + item.getEventPhotoUrl();
		
		CivicinityDrawableManager dm = new CivicinityDrawableManager(this, mSpinner, mPhotoImg);
		dm.fetchDrawableOnThread(imagePath);
		mSpinnerTxt.setVisibility(View.GONE);
		
	    // for description
		mDescription.setText("\"" + item.getEventDescription() + "\".");
		//mCategory.setText(item.getEventCategory());
	    
		// for date
		SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy HH:mm");
        Date resultdate = new Date(Long.parseLong(item.getEventDate()) * 1000);
		mDate.setText(sdf.format(resultdate));
		
		// check-in count text
		mCheckinNumTxt.setText(item.getEventCheckInCnt() + " people checked-in.");
		
		// make the marker invisible for the same user
		if(mPref.getString("username", "Guest").equals(item.getEventUsername())) {
			mCheckInBtn.setVisibility(View.GONE);
		}
		
		// check-in button clicks
		mCheckInBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				if(mPref.getString("username", "Guest").equals("Guest")) {
					Toast.makeText(CivicinityShareInfo.this, "Guests are not able to check-in.", Toast.LENGTH_SHORT).show();
				}
				else {
					// checking user's location.
					mLocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
					Location loc = mLocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
					
					mLatitude = loc.getLatitude();
					mLongitude = loc.getLongitude();
					
					//if(loc.getAccuracy() > 100) {
					//	Toast.makeText(CivicinityShareInfo.this, "Your location is not accurate enough, can't calculate.", Toast.LENGTH_SHORT).show();
					//}
					//else {
						// compare the distance between the point and the user, if it is close enough(how much?), then check-in possible.
						float []distance = new float[1];
						Location.distanceBetween(mLatitude, mLongitude, item.getEventLatitude(), item.getEventLongitude(), distance);
						
						/*
						if(distance[0] < 30) {
							Toast.makeText(CivicinityShareInfo.this, String.format("You are close enough! Check in! %5.1f miles away", distance[0] * 0.0006), Toast.LENGTH_SHORT).show();
							
							
							
						}
						else {
							Toast.makeText(CivicinityShareInfo.this, String.format("You are NOT close enough! %5.1f miles away", distance[0] * 0.0006), Toast.LENGTH_SHORT).show();
							
							
						}
						*/
						
						// guest can't check-in
						if(mPref.getBoolean("guest_mode", false)) {
							Toast.makeText(CivicinityShareInfo.this, "Guests are not able to check-in", Toast.LENGTH_SHORT).show();
							return;
						}
						
						new AlertDialog.Builder(CivicinityShareInfo.this)
				   		.setTitle("Check-in")
				   		.setMessage("You are close enough to check-in this place. Proceed?")
				   		.setPositiveButton("Check-in", new DialogInterface.OnClickListener() {
				   			public void onClick(DialogInterface dialog, int whichButton) {
				   		
				   				showDialog(2);
				   				
				   				// update the comment info to the system.
								Thread uploadThread = new Thread() {
									@Override
									public void run() {
									
										doUpload(2);
										mCompleteHandler.sendEmptyMessage(2);
									}
								};
								uploadThread.start();
						
				   			}
				   		})
				   		.setNegativeButton("Back", null)
				   		.show();
					
					//}
				}
			}
		});
		
		// if comment count is 0, disable the seeCommentBtn
		if(mCommentCntValue == 0) {
			mSeeCommentBtn.setEnabled(false);
		}
		
		// handle button clicks
		mCommentBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(mPref.getBoolean("guest_mode", false)) {
					Toast.makeText(CivicinityShareInfo.this, "Access denied - 'GUEST' login", Toast.LENGTH_SHORT).show();
				} 
				else {
					if(mCommentTxt.getText().toString().equals("")) {
						Toast.makeText(CivicinityShareInfo.this, "Please add comment.", Toast.LENGTH_SHORT).show();
					}
					else {
						//Toast.makeText(CivicinityShareInfo.this, "Adding your comment.", Toast.LENGTH_SHORT).show();
						
						showDialog(0);
						
						// update the comment info to the system.
						Thread uploadThread = new Thread() {
							@Override
							public void run() {
							
								doUpload(0);
								mCompleteHandler.sendEmptyMessage(0);
							}
						};
						
						uploadThread.start();
					}
				}
			}
		});
		
		// user cannot recommend self-posts.
		if(mPref.getString("username", "").equals(item.getEventUsername())) {
			mRecommendBtn.setVisibility(View.GONE);
		}
		
		mRecommendBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(mPref.getBoolean("guest_mode", false)) {
					Toast.makeText(CivicinityShareInfo.this, "Access denied - 'GUEST' login", Toast.LENGTH_SHORT).show();
				}
				else {
					new AlertDialog.Builder(CivicinityShareInfo.this)
			   		.setTitle("Like")
			   		.setMessage("Do you like this post?")
			   		.setPositiveButton("Like", new DialogInterface.OnClickListener() {
			   			public void onClick(DialogInterface dialog, int whichButton) {
			   				
			   				showDialog(1);
			   				
			   				Thread likeThread = new Thread() {
			   					@Override
								public void run() {
								
			   						doUpload(1);
									mCompleteHandler.sendEmptyMessage(1);
								}
			   				};
			   				
			   				likeThread.start();
			   			}
			   		})
			   		.setNegativeButton("Back", new DialogInterface.OnClickListener() {
			   			public void onClick(DialogInterface dialog, int whichButton) {
			   			}
			   		})
			   		.show();
				}
			}
		});
		
		mSeeCommentBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				mSeeCommentBtn.setEnabled(false);
				mGlobalRelativeLayout.setVisibility(View.VISIBLE);
				
				// download comments from the server and display them.
				new downloadShareComment().execute();
	
			}
		});
		
	    // for comment count display
	    if(item.getEventCommentCnt() == 0 || item.getEventCommentCnt() == 1) {
	    	mCommentCnt.setText(item.getEventCommentCnt() + " comment on this post.");
	    }
	    else {
	    	mCommentCnt.setText(item.getEventCommentCnt() + " comments on this post.");
	    }
	    
	    mRecommendTxt.setText(item.getEventLike() + " people like it.");
	    
	    if(item.getEventLike() == 1) {
	    	mRecommendBtn.setVisibility(View.GONE);
	    }
	}
	
	private void letsCheckin() {
		
		
	}
	
	/**
	 * Upload new comment to the server, using thread
	 */
	private void doUpload(int what) {
		
		// comment
		if(what == 0) {
			// remove all opened view
			long timeInMillis = System.currentTimeMillis();
			
			UploadHandler uHandler = new UploadHandler(this);
			uHandler.uploadComments(mEventID, timeInMillis, mCommentTxt.getText().toString());
		}
		// like
		else if(what == 1) {

			UploadHandler uHandler = new UploadHandler(this);
			// user_id set to 1.
			uHandler.uploadLike(mEventID, 1);
		}
		// check-in
		else if(what == 2) {
			long timeInMillis = System.currentTimeMillis();
			// upload check-in to the server.
			UploadHandler uHandler = new UploadHandler(CivicinityShareInfo.this);
			uHandler.uploadCheckIn(mEventID, timeInMillis);
		}
	}
	
	/**
	 * Handler with a thread
	 */
	private Handler mCompleteHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if(msg.what == 0) {
				
				// make the comment button enable
				mSeeCommentBtn.setEnabled(true);
				
				// remove all attached view from mGlobalLinearLayout and
				// make the dynamic layout invisible.				
				mGlobalRelativeLayout.setVisibility(View.GONE);
				mGlobalLinearLayout.removeAllViews();

				// update the value and start activity again.
				Toast.makeText(CivicinityShareInfo.this, "Your comment is added.", Toast.LENGTH_SHORT).show();
				mDB.updateShareOthersComment(mEventID, mCommentCntValue+1);
				mCommentTxt.setText("");
				mUsernameTxt.setFocusable(true);
				
				dismissDialog(0);
				
				// hide keyboard window
				InputMethodManager iManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				iManager.hideSoftInputFromWindow(mCommentTxt.getWindowToken(), 0);

				onResume();
			}
			else if(msg.what == 1) {
				// change the LIKE value into 1.
				mDB.updateShareLike(mEventID);
				
				dismissDialog(1);
				
				onResume();
			}
			else if(msg.what == 2) {
				
				// change the check-in value.
				mDB.updateShareCheckIn(mEventID, item.getEventCheckInCnt());
				
				dismissDialog(2);
				
				onResume();
			}
		}
	};
	
	/**
	 * Download share components from the server
	 * @author kyunghan
	 *
	 */
	class downloadShareComment extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... unused) {
			// TODO Auto-generated method stub
			
			DownloadHandler dHandler = new DownloadHandler();
			String getResponse = dHandler.downloadJson(Constants.DOWNLOAD_SHARE_COMMENTS + "?share_id=" + mEventID);

			Log.i("K", "getResponse : " + getResponse);
			
			mGlobalLinearLayout = new LinearLayout(CivicinityShareInfo.this);
			mGlobalLinearLayout.setOrientation(LinearLayout.VERTICAL);
			mGlobalLinearLayout.setFocusable(true);
			
			try{
				JSONObject jObj = new JSONObject(getResponse);
				
				if(jObj.getBoolean("success")) {
					JSONArray jsonAry = new JSONArray(jObj.getString("results"));
					
					for(int i = 0; i < jsonAry.length(); i++){
						
						// dynamically adding comments
						LinearLayout ll = new LinearLayout(CivicinityShareInfo.this);
						LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
						lp1.setMargins(5, 1, 3, 2);
						
						ll.setLayoutParams(lp1);
						ll.setOrientation(LinearLayout.VERTICAL);

						ll.setBackgroundResource(R.drawable.bubble_share_button_icon);
						
						LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
						lp2.setMargins(5, 1, 1, 0);

						TextView tv1 = new TextView(CivicinityShareInfo.this);
						tv1.setLayoutParams(lp2);
						SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss");
				        Date resultdate = new Date(Long.parseLong(jsonAry.getJSONObject(i).getString("dates")) * 1000);
				        
						tv1.setText("By " + jsonAry.getJSONObject(i).getString("username") + " - " + sdf.format(resultdate));
						
						TextView tv2 = new TextView(CivicinityShareInfo.this);
						tv2.setText(jsonAry.getJSONObject(i).getString("description"));
						tv2.setLayoutParams(lp2);
						tv2.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
						tv2.setTextSize(16);
						
						LinearLayout.LayoutParams lp3 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, 1);
						View view = new View(CivicinityShareInfo.this);
						view.setLayoutParams(lp3);
						view.setBackgroundResource(R.drawable.blue_bar);
						
						ll.addView(tv2);
						ll.addView(tv1);
						ll.addView(view);
						
						mGlobalLinearLayout.addView(ll);
						
					}
					Log.d("K", "download shared info : success to store into db");
				}
			} catch(Exception e){
				Log.i("K", "Error when downloading the comments");
				 e.printStackTrace();
			}

			return null;
		}
		
		@Override
	  	protected void onPostExecute(Void unused) {
		
			mGlobalRelativeLayout.addView(mGlobalLinearLayout);
			
			// hide the spinner and textview
			ProgressBar dSpinner = (ProgressBar)findViewById(R.id.dynamic_spinner);
			TextView dText = (TextView)findViewById(R.id.dynamic_loading_text);
			
			dSpinner.setVisibility(View.GONE);
			dText.setVisibility(View.GONE);
		}		
	}
	
	/**
	 * Override generating a dialog box.
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		
		if(Looper.myLooper() == null)
			Looper.prepare();
		
		switch(id) {
		case 0: case 1: case 2:
			mProgress = new ProgressDialog(this);
			mProgress.setTitle("Uploading");
			mProgress.setMessage("Please wait...:)");
			mProgress.setCancelable(true);
			
			return mProgress;
		}
		return null;
	}
}
